function J = jeval_2(fid,model,cgp)

% JEVAL Evaluate minimization criterion
%
% Expects the following:
%    * Either MODEL.{AMP,EXP} or MODEL.{PPP,IX,IY} -- image parameters
%    * MODEL.RESO
%    * FID.N -- # of voxels (optional)
%    * FID.SIG
%    * FID.EST
%    * CGP.ALPHAM
%    * CGP.ALPHAF

if isfield(fid,'N') 
    NF = fid.N;
else
    NF = length(fid.sig);
end
if isfield(model,'N') 
    NM = model.N; 
else
    NM = length(model.pvec)/2; 
end
sigdiff1 = fid.est1(1:NF) - fid.sig1(1:NF);
sigdiff2 = fid.est2(1:NF) - fid.sig2(1:NF);
alphaM = cgp.alphaM;
alphaf = cgp.alphaf;

J = sigdiff1*sigdiff1'+ sigdiff2*sigdiff2';
if (alphaM ~= 0 || alphaf ~= 0)
    L = [ 0 1 0; 1 -4 1; 0 1 0];
    p_image = zeros(model.reso);
end
if (alphaM ~= 0)
    p_image1(model.ix+model.reso*(model.iy-1)) = model.pvec(1:NM);
    p_grad1 = conv2(conv2(p_image1,L,'valid'),L);
    p_image2(model.ix+model.reso*(model.iy-1)) = model.pvec(NM+1:2*NM);
    p_grad2 = conv2(conv2(p_image2,L,'valid'),L);    
    J = J + alphaM*(p_grad1(:)'*p_grad1(:)+p_grad2(:)'*p_grad2(:));
end
if (alphaf ~= 0)
    p_image(model.ix+model.reso*(model.iy-1)) = model.pvec(2*NM+1:3*NM);
    p_grad = conv2(conv2(p_image,L,'valid'),L);
    pgr_power = real(p_grad(:))'*real(p_grad(:));
    pgi_power = imag(p_grad(:))'*imag(p_grad(:));
    if (isreal(alphaf))
       J = J + alphaf*(model.wfr^2*pgr_power + model.wfi^2*pgi_power);
    else
       J = J + real(alphaf)*model.wfr^2*pgr_power + imag(alphaf)*model.wfi^2*pgi_power;
    end
end